package jmine.tec.web.servlet.cipher;

import java.io.IOException;

import javax.crypto.Cipher;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import jmine.tec.utils.cripto.key.impl.KeyStoreKeyPairHolder;
import jmine.tec.utils.cripto.key.impl.KeyStorePublicKeyLocator;
import jmine.tec.utils.cripto.key.impl.StaticPasswordManager;
import jmine.tec.utils.cripto.key.store.KeyStoreReader;
import jmine.tec.utils.io.IOUtils;
import jmine.tec.web.servlet.cipher.challenge.AssertionFactory;
import jmine.tec.web.servlet.cipher.impl.InitialSecureCommunicationHandler;
import junit.framework.Assert;

public class SecureCommunicationFilterTester extends SecureCommunicationFilter {

    public static volatile boolean restart = false;
    public static volatile boolean expire;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        InitialSecureCommunicationHandler initial = new InitialSecureCommunicationHandler();
        initial.setAssertionFactory(new AssertionFactory(10));
        initial.setChunkSize(35);
        KeyStorePublicKeyLocator publicKeyLocator = new KeyStorePublicKeyLocator();
        try {
            KeyStoreReader r = new KeyStoreReader();
            r.setPasswordManager(new StaticPasswordManager("password"));
            r.initialize(getClass().getResourceAsStream("/serverStore.jks"));
            publicKeyLocator.setKeyStoreReader(r);
            initial.setPublicKeyLocator(publicKeyLocator);
            initial.setCipher(Cipher.getInstance("RSA"));
            KeyStoreKeyPairHolder holder = new KeyStoreKeyPairHolder();
            holder.setKeyStoreReader(r);
            holder.setKeyAlias("serverKey");
            initial.setKeyPairFactory(holder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        setInitialSecureCommunication(initial);
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        super.doFilter(request, response, chain);
        if(expire) {
            ((HttpServletRequest) request).getSession().invalidate();
            expire = false;
        }
    }
    
    @Override
    protected SecureCommunicationHandler getCommunication(HttpServletRequest httpRequest) {
        if(restart) {
            httpRequest.getSession().removeAttribute(COMM_IN_SESSION);
            restart = false;
        }
        SecureCommunicationHandler handler = super.getCommunication(httpRequest);
        if(handler != null) {
            //try to serialize
            SecureCommunicationHandler clone = IOUtils.deepClone(handler);
            Assert.assertEquals(handler.getClass(), clone.getClass());
        }
        return handler;
    }

}
